#include "book.h"
#include"tcpclient.h"
#include<QInputDialog>
#include<QMessageBox>
#include<QFileDialog>
#include"opewidget.h"
Book::Book(QWidget *parent) : QWidget(parent)
{
    m_strEnterDir.clear();
    m_pTimer = new QTimer;
    m_bDownload = false;

    m_pBookListW = new QListWidget;

    m_pReturnPB = new QPushButton("返回");
    m_pCreateDirPB = new QPushButton("创建文件夹");
    m_pDelDirPB = new QPushButton("删除文件夹");
    m_pRenamePB = new QPushButton("重命名文件夹");
    m_pFlushFilePB = new QPushButton("刷新文件夹");

    QVBoxLayout *pVlayout = new QVBoxLayout;
    pVlayout->addWidget(m_pReturnPB);
    pVlayout->addWidget(m_pCreateDirPB);
    pVlayout->addWidget(m_pDelDirPB);
    pVlayout->addWidget(m_pRenamePB);
    pVlayout->addWidget(m_pFlushFilePB);

    m_pUpLoadPB = new QPushButton("上传文件");
    m_pDownLoadPB = new QPushButton("下载文件");
    m_pDelFilePB = new QPushButton("删除文件");
    m_pShareFilePB = new QPushButton("分享文件");

    QVBoxLayout *pVlayout_ = new QVBoxLayout;
    pVlayout_->addWidget(m_pUpLoadPB);
    pVlayout_->addWidget(m_pDownLoadPB);
    pVlayout_->addWidget(m_pDelFilePB);
    pVlayout_->addWidget(m_pShareFilePB);

    QHBoxLayout *pMain = new QHBoxLayout;
    pMain->addWidget(m_pBookListW);
    pMain->addLayout(pVlayout);
    pMain->addLayout(pVlayout_);

    setLayout(pMain);

    connect(m_pCreateDirPB,&QPushButton::clicked,this,&Book::createDir);
    connect(m_pFlushFilePB,&QPushButton::clicked,this,&Book::flushFile);
    connect(m_pDelDirPB,&QPushButton::clicked,this,&Book::delDir);
    connect(m_pRenamePB,&QPushButton::clicked,this,&Book::renameFile);
    connect(m_pBookListW,&QListWidget::doubleClicked,this,&Book::enterDir);
    connect(m_pReturnPB,&QPushButton::clicked,this,&Book::returnPre);
    connect(m_pUpLoadPB,&QPushButton::clicked,this,&Book::uploadFile);
    //定时器时间一到就调用uploadFileData函数
    connect(m_pTimer,&QTimer::timeout,this,&Book::uploadFileData);
    connect(m_pDelFilePB,&QPushButton::clicked,this,&Book::delRegFile);
    connect(m_pDownLoadPB,&QPushButton::clicked,this,&Book::downloadFile);
    connect(m_pShareFilePB,&QPushButton::clicked,this,&Book::shareFile);

}

void Book::updateFileList(const PDU *pdu)
{
    if(NULL == pdu)
    {
        return;
    }
    FileInfo *pFileInfo = NULL;
    int iCount = pdu->uiMsgLen/sizeof (FileInfo);
    for(int i =0;i<iCount;i++)
    {

        pFileInfo = (FileInfo*)(pdu->caMsg)+i;
        //qDebug()<<pFileInfo->caFileName;
        QListWidgetItem *pItem = new QListWidgetItem;
        if(0 == pFileInfo->iFileType)
        {
            pItem->setIcon(QIcon(QPixmap(":/map/file.jpg")));
        }
        else if(1 == pFileInfo->iFileType)
        {
            pItem->setIcon(QIcon(QPixmap(":/map/subFile.jpg")));
        }
        pItem->setText(pFileInfo->caFileName);
        m_pBookListW->addItem(pItem);
    }
}

void Book::clearEnterDir()
{
    m_strEnterDir.clear();
}

QString Book::enterdir()
{
    return m_strEnterDir;
}

void Book::setDownloadStatus(bool status)
{
    m_bDownload = status;
}

bool Book::getDownloadStatus()
{
    return m_bDownload;
}

QString Book::getSaveFilePath()
{
    return m_strSaveFilePath;
}

void Book::createDir()
{
    QString strNewDir = QInputDialog::getText(this,"新建文件夹","新文件夹名字");
    if(!strNewDir.isEmpty())
    {
        if(strNewDir.size()>32)
        {
            QMessageBox::warning(this,"新建文件夹","新文件夹名字不能超过32个字节!");
        }
        else
        {
            QString strName = TcpClient::getInstance().loginName();
            QString strCurPath = TcpClient::getInstance().curPath();
            PDU *pdu = mkPDU(strCurPath.size()+1);
            pdu->uiMsgType = ENUM_MSG_TYPE_CREATE_DIR_REQUEST;
            strncpy(pdu->caData,strName.toStdString().c_str(),strName.size());
            strncpy(pdu->caData+32,strNewDir.toStdString().c_str(),strNewDir.size());
            memcpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());

            TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
            free(pdu);
            pdu = NULL;
        }

    }
    else
    {
        QMessageBox::warning(this,"新建文件夹","新文件夹名字不能为空");
    }

}

void Book::flushFile()
{
    QString strCurPath = TcpClient::getInstance().curPath();
    PDU *pdu = mkPDU(strCurPath.size()+1);
    pdu->uiMsgType = ENUM_MSG_TYPE_FLUSH_FILE_REQUEST;
    strncpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());
    TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
    free(pdu);
    pdu = NULL;
}

void Book::delDir()
{
    QString strCurPath = TcpClient::getInstance().curPath();
    QListWidgetItem *pItem = m_pBookListW->currentItem();
    if(NULL == pItem)
    {
        QMessageBox::warning(this,"删除文件","请选择要删除的文件！");
    }
    else
    {
        QString strDelName = pItem->text();
        PDU *pdu = mkPDU(strCurPath.size()+1);
        pdu->uiMsgType = ENUM_MSG_TYPE_DEL_DIR_REQUEST;
        strncpy(pdu->caData,strDelName.toStdString().c_str(),strDelName.size());
        memcpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());
        TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
        free(pdu);
        pdu = NULL;
    }
}

void Book::renameFile()
{
    QString strCurPath = TcpClient::getInstance().curPath();
    QListWidgetItem *pItem = m_pBookListW->currentItem();
    if(NULL == pItem)
    {
        QMessageBox::warning(this,"重命名文件","请选择要重命名的文件！");
    }
    else
    {
        QString strOldName = pItem->text();
        QString strNewName = QInputDialog::getText(this,"重命名文件","请输入新文件名：？");
        if(!strNewName.isEmpty())
        {
            PDU *pdu = mkPDU(strCurPath.size()+1);
            pdu->uiMsgType = ENUM_MSG_TYPE_RENAME_FILE_REQUEST;
            strncpy(pdu->caData,strOldName.toStdString().c_str(),strOldName.size());
            strncpy(pdu->caData+32,strNewName.toStdString().c_str(),strNewName.size());
            memcpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());
            TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
            free(pdu);
            pdu = NULL;
        }
        else
        {
            QMessageBox::warning(this,"重命名文件","新文件名不能为空！");
        }
    }
}

void Book::enterDir(const QModelIndex &index)
{
    //获取QListWideget上点击的文件名字
    QString strDirName = index.data().toString();
    m_strEnterDir = strDirName;
    QString strCurPath = TcpClient::getInstance().curPath();
    PDU *pdu = mkPDU(strCurPath.size()+1);
    pdu->uiMsgType = ENUM_MSG_TYPE_ENTER_DIR_REQUEST;
    strncpy(pdu->caData,strDirName.toStdString().c_str(),strDirName.size());
    memcpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());

    TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
    free(pdu);
    pdu = NULL;
}

void Book::returnPre()
{
    QString strCurPath = TcpClient::getInstance().curPath();
    qDebug()<<"strCurPath:"<<strCurPath;
    QString strRootPath = "./home/" + TcpClient::getInstance().loginName();
    qDebug()<<"strRootPath:"<<strRootPath;
    if(strCurPath == strRootPath)
    {
        QMessageBox::warning(this,"返回","返回失败：已经是根目录！");
    }
    else
    {
        // "./aa/bb/cc" --> "./aa/bb"
        //lastIndexOf函数是获取最后一个'/'在字符串strCurPath中的索引，在上面例子中index=7
        int index = strCurPath.lastIndexOf('/');
        //从索引值为index的字符开始，往后移除strCuParh.size()-index个字符，即移除最后一个'/'后的所有字符
        strCurPath.remove(index,strCurPath.size() - index);
        TcpClient::getInstance().setCurPath(strCurPath);

        //因为和刷新文件功能一样调用都调用了flushFile函数，所以要清空变量m_strEnterDir
        clearEnterDir();
        //调用刷新文件的函数
        flushFile();
    }
}

void Book::uploadFile()
{
    QString strCurPath = TcpClient::getInstance().curPath();
    m_strUploadFilePath = QFileDialog::getOpenFileName(); //打开文件的路径
    qDebug()<<"m_strUploadFilePath:"<<m_strUploadFilePath;
    if(!m_strUploadFilePath.isEmpty()){
        int index = m_strUploadFilePath.lastIndexOf('/');
        //获取strUploadFilePath最后一个‘/’后的字符串
        QString strFileName = m_strUploadFilePath.right(m_strUploadFilePath.size()-index -1);

        QFile file(m_strUploadFilePath);
        qint64 fileSize = file.size();  //获得文件大小
        qDebug()<<"文件大小:"<<fileSize;
        QString strCurPath = TcpClient::getInstance().curPath();
        PDU *pdu = mkPDU(strCurPath.size()+1);
        pdu->uiMsgType = ENUM_MSG_TYPE_UPLOAD_FILE_REQUEST;
        memcpy(pdu->caMsg,strCurPath.toStdString().c_str(),strCurPath.size());
        //lld表示长整型long long int，file.size()返回的是长整型
        sprintf(pdu->caData,"%s %lld",strFileName.toStdString().c_str(),fileSize);

        TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
        free(pdu);
        pdu = NULL;
        m_pTimer->start(1000);  //1000ms，1000毫秒后开始上传文件(调用uploadFileData()函数）

    }
    else
    {
        QMessageBox::warning(this,"上传文件","请选择要上传的文件！");
    }
}

void Book::uploadFileData()
{
    m_pTimer->stop();//停止计时
    QFile file(m_strUploadFilePath);
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this,"上传文件","打开文件失败！");
        return;
    }

    char *pBuffer = new char[4096];
    qint64 ret = 0;
    while(true)
    {
        ret = file.read(pBuffer,4096);
        qDebug()<<"上传的字节数："<<ret;
        //ret为读取到的字节数
        if(ret>0 && ret <= 4096)
        {
            TcpClient::getInstance().getTcpSocket().write(pBuffer,ret);
        }
        else if(0 == ret)
        {
            break;
        }
        else
        {
            QMessageBox::warning(this,"上传文件","上传文件失败！");
            break;
        }
    }
    file.close();
    delete []pBuffer;
    pBuffer = NULL;
}

void Book::delRegFile()
{
    QString strCurPath = TcpClient::getInstance().curPath();
    QListWidgetItem *pItem = m_pBookListW->currentItem();
    qDebug()<<"pItem："<<pItem;
    if(NULL == pItem)
    {
        QMessageBox::warning(this,"删除文件","请选择要删除的文件！");
    }
    else
    {
        qDebug()<<"进入删除文件："<<strCurPath;
        QString strDelName = pItem->text();
        PDU *pdu = mkPDU(strCurPath.size()+1);
        pdu->uiMsgType = ENUM_MSG_TYPE_DEL_FILE_REQUEST;
        strncpy(pdu->caData,strDelName.toStdString().c_str(),strDelName.size());
        memcpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());
        TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
        free(pdu);
        pdu = NULL;
    }
}

void Book::downloadFile()
{

    QListWidgetItem *pItem = m_pBookListW->currentItem();
    //qDebug()<<"pItem："<<pItem;
    if(NULL == pItem)
    {
        QMessageBox::warning(this,"下载文件","请选择要下载的文件！");
    }
    else
    {
        QString strSaveFilePath = QFileDialog::getSaveFileName();
        if(strSaveFilePath.isEmpty())
        {
            QMessageBox::warning(this,"下载文件","请指定要保存文件的位置！");
            m_strSaveFilePath.clear();
        }
        else
        {
            m_strSaveFilePath = strSaveFilePath;

        }

        QString strCurPath = TcpClient::getInstance().curPath();
        QString strdownLoadName = pItem->text();
        PDU *pdu = mkPDU(strCurPath.size()+1);
        pdu->uiMsgType = ENUM_MSG_TYPE_DOWNLOAD_FILE_REQUEST;
        strncpy(pdu->caData,strdownLoadName.toStdString().c_str(),strdownLoadName.size());
        memcpy((char*)(pdu->caMsg),strCurPath.toStdString().c_str(),strCurPath.size());
        TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
        free(pdu);
        pdu = NULL;

    }
}

void Book::shareFile()
{
    Friend *pFriend = OpeWidget::getInstance().getFriend();
    QListWidget *pFriendList = pFriend->getFriendList();
}





